/**
 * 模型对比状态管理
 * 使用Zustand进行全局状态管理
 */

import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { comparisonWebSocketService, ComparisonProgress } from '../services/comparison.websocket.service';

export interface ModelResult {
  model: string;
  content: string;
  tokens: number;
  time: number;
  score?: Record<string, number>;
  status: 'pending' | 'generating' | 'completed' | 'failed' | 'timeout';
  error?: string;
}

export interface ComparisonSession {
  sessionId: string;
  prompt: string;
  systemPrompt?: string;
  models: Array<{
    name: string;
    version: string;
    parameters: Record<string, any>;
  }>;
  results: ModelResult[];
  selectedModel?: string;
  mergedContent?: string;
  status: 'pending' | 'processing' | 'completed' | 'failed' | 'partial';
  createdAt: string;
  updatedAt: string;
  aggregation?: Record<string, any>;
}

interface ComparisonState {
  // 当前会话
  currentSession: ComparisonSession | null;
  
  // 历史会话
  sessions: ComparisonSession[];
  
  // WebSocket连接状态
  wsConnected: boolean;
  wsConnecting: boolean;
  
  // 加载状态
  loading: boolean;
  error: string | null;
  
  // Actions
  createComparison: (prompt: string, models: any[], systemPrompt?: string) => Promise<void>;
  loadSession: (sessionId: string) => Promise<void>;
  selectModel: (model: string) => Promise<void>;
  saveMergedContent: (content: string) => void;
  connectWebSocket: (sessionId: string) => Promise<void>;
  disconnectWebSocket: () => void;
  updateResult: (model: string, result: Partial<ModelResult>) => void;
  updateSessionStatus: (status: ComparisonSession['status']) => void;
  clearError: () => void;
  reset: () => void;
}

export const useComparisonStore = create<ComparisonState>()(
  devtools(
    persist(
      (set, get) => ({
        // 初始状态
        currentSession: null,
        sessions: [],
        wsConnected: false,
        wsConnecting: false,
        loading: false,
        error: null,

        // 创建对比
        createComparison: async (prompt, models, systemPrompt) => {
          set({ loading: true, error: null });
          
          try {
            // 调用API创建对比
            const response = await fetch('/api/v1/comparisons/create', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
              },
              body: JSON.stringify({
                prompt,
                models,
                system_prompt: systemPrompt
              })
            });

            if (!response.ok) {
              throw new Error('创建对比失败');
            }

            const data = await response.json();
            
            // 创建新会话
            const newSession: ComparisonSession = {
              sessionId: data.session_id,
              prompt,
              systemPrompt,
              models,
              results: models.map(m => ({
                model: m.name,
                content: '',
                tokens: 0,
                time: 0,
                status: 'pending'
              })),
              status: 'processing',
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString()
            };

            set(state => ({
              currentSession: newSession,
              sessions: [newSession, ...state.sessions],
              loading: false
            }));

            // 连接WebSocket
            await get().connectWebSocket(data.session_id);

          } catch (error) {
            set({ 
              loading: false, 
              error: error instanceof Error ? error.message : '创建对比失败' 
            });
          }
        },

        // 加载会话
        loadSession: async (sessionId) => {
          set({ loading: true, error: null });
          
          try {
            const response = await fetch(`/api/v1/comparisons/${sessionId}`, {
              headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
              }
            });

            if (!response.ok) {
              throw new Error('加载会话失败');
            }

            const session = await response.json();
            
            set({
              currentSession: session,
              loading: false
            });

            // 如果会话还在处理中，连接WebSocket
            if (session.status === 'processing') {
              await get().connectWebSocket(sessionId);
            }

          } catch (error) {
            set({ 
              loading: false, 
              error: error instanceof Error ? error.message : '加载会话失败' 
            });
          }
        },

        // 选择模型
        selectModel: async (model) => {
          const { currentSession } = get();
          if (!currentSession) return;

          try {
            const response = await fetch(`/api/v1/comparisons/${currentSession.sessionId}/select`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
              },
              body: JSON.stringify({ model })
            });

            if (!response.ok) {
              throw new Error('选择模型失败');
            }

            set(state => ({
              currentSession: state.currentSession ? {
                ...state.currentSession,
                selectedModel: model,
                updatedAt: new Date().toISOString()
              } : null
            }));

          } catch (error) {
            set({ 
              error: error instanceof Error ? error.message : '选择模型失败' 
            });
          }
        },

        // 保存合并内容
        saveMergedContent: (content) => {
          set(state => ({
            currentSession: state.currentSession ? {
              ...state.currentSession,
              mergedContent: content,
              updatedAt: new Date().toISOString()
            } : null
          }));
        },

        // 连接WebSocket
        connectWebSocket: async (sessionId) => {
          const { wsConnected, wsConnecting } = get();
          
          if (wsConnected || wsConnecting) {
            return;
          }

          set({ wsConnecting: true });

          try {
            // 设置事件监听器
            comparisonWebSocketService.removeAllListeners();
            
            comparisonWebSocketService.on('connected', () => {
              set({ wsConnected: true, wsConnecting: false });
            });

            comparisonWebSocketService.on('disconnected', () => {
              set({ wsConnected: false, wsConnecting: false });
            });

            comparisonWebSocketService.on('progress', (data: ComparisonProgress) => {
              if (data.model && data.status) {
                get().updateResult(data.model, { status: data.status as any });
              }
            });

            comparisonWebSocketService.on('result', (data: ComparisonProgress) => {
              if (data.model && data.result) {
                get().updateResult(data.model, data.result);
              }
            });

            comparisonWebSocketService.on('complete', (data: ComparisonProgress) => {
              set(state => ({
                currentSession: state.currentSession ? {
                  ...state.currentSession,
                  status: data.status as any || 'completed',
                  aggregation: data.aggregation,
                  updatedAt: new Date().toISOString()
                } : null
              }));
            });

            comparisonWebSocketService.on('error', (data: ComparisonProgress) => {
              set({ error: data.error || 'WebSocket错误' });
            });

            // 连接WebSocket
            await comparisonWebSocketService.connect(sessionId);

          } catch (error) {
            set({ 
              wsConnecting: false,
              error: error instanceof Error ? error.message : 'WebSocket连接失败' 
            });
          }
        },

        // 断开WebSocket
        disconnectWebSocket: () => {
          comparisonWebSocketService.disconnect();
          set({ wsConnected: false, wsConnecting: false });
        },

        // 更新结果
        updateResult: (model, result) => {
          set(state => {
            if (!state.currentSession) return state;

            const updatedResults = state.currentSession.results.map(r => 
              r.model === model ? { ...r, ...result } : r
            );

            return {
              currentSession: {
                ...state.currentSession,
                results: updatedResults,
                updatedAt: new Date().toISOString()
              }
            };
          });
        },

        // 更新会话状态
        updateSessionStatus: (status) => {
          set(state => ({
            currentSession: state.currentSession ? {
              ...state.currentSession,
              status,
              updatedAt: new Date().toISOString()
            } : null
          }));
        },

        // 清除错误
        clearError: () => {
          set({ error: null });
        },

        // 重置状态
        reset: () => {
          get().disconnectWebSocket();
          set({
            currentSession: null,
            wsConnected: false,
            wsConnecting: false,
            loading: false,
            error: null
          });
        }
      }),
      {
        name: 'comparison-storage',
        partialize: (state) => ({
          sessions: state.sessions.slice(0, 10) // 只保存最近10个会话
        })
      }
    )
  )
);